package com.epam.tcs.actions.pages;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.ObjectNotFoundException;

import com.epam.tcs.actions.BreadCrumb;
import com.epam.tcs.dao.factory.DAO;
import com.epam.tcs.dao.hibernate.entities.Practice;
import com.epam.tcs.dao.hibernate.entities.Theme;

public class PracticePage extends PageAbstract {

	@Override
	public void doExec(HttpServletRequest req, HttpServletResponse res) {
		String target = req.getRequestURI().substring(
				req.getContextPath().length());

		String[] tarr = target.split("/");
		BreadCrumb.add(req, res, "Практики", "/tcs/practice");
		try {
			if ((tarr.length == 4) && tarr[3].equals("add")) {
				addPractice(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("del")) {
				delPractice(req, res);
			} else if ((tarr.length == 4) && tarr[3].equals("edit")) {
				editPractice(req, res);
			} else {
				listPractice(req, res);
			}
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void addPractice(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		BreadCrumb.add(req, res, "Добавить практику", "/tcs/practice/add");
		DAO<Theme> theme = dao.getThemeDAO();
		if (req.getMethod() == "POST" && this.validatePracticeForm(req)) {
			DAO<Practice> practice = dao.getPracticeDAO();
			Practice pr = new Practice();
			pr.setName(req.getParameter("caption"));
			//pr.setDescription(req.getParameter("description"));
			Theme t = theme
					.getElement(Long.parseLong(req.getParameter("theme")));
			pr.setTheme(t);
			if (practice.addElement(pr) != 0L) {
				req.setAttribute("message", "Практика \"" + pr.getName()
						+ "\" успешно добавлена.");
			}
		}
		req.setAttribute("widget", "add_practice");
		req.setAttribute("action", "/tcs/practice/add");
		req.getSession().setAttribute("listThemes", theme.getAllElements());
		outputPage("practice/practice_form.jsp", req, res);
	}

	private void delPractice(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		// TODO For tVinsent
		DAO<Practice> practice = dao.getPracticeDAO();
		ArrayList<String> practices_name = new ArrayList<String>();
		for (Enumeration<String> e = req.getParameterNames(); e
				.hasMoreElements();) {
			String[] s = ((String) e.nextElement()).split("_");
			System.out.println(s);
			Practice practice_element = (Practice) practice.getElement(Long
					.parseLong(s[2]));
			practices_name.add(practice_element.getName());
			practice.deleteElement(practice.getElement(Long.parseLong(s[2])));
		}
		req.setAttribute("widget", "practice");
		req.setAttribute("message",
				"Удалены темы: " + practices_name.toString());
		req.getSession()
				.setAttribute("listPractice", practice.getAllElements());
		outputPage("practice/practice.jsp", req, res);
	}

	private void editPractice(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		if (req.getParameter("practice_id") != null
				&& Long.parseLong(req.getParameter("practice_id")) > 0) {
			DAO<Practice> practice = dao.getPracticeDAO();
			try {
				Practice pr = practice.getElement(Long.parseLong(req
						.getParameter("practice_id")));
				BreadCrumb
						.add(req,
								res,
								"Изменить практику " + pr.getName(),
								"/tcs/practice/edit?practice_id="
										+ pr.getLecPracId());
				DAO<Theme> theme = dao.getThemeDAO();
				if (req.getMethod() == "POST" && this.validatePracticeForm(req)) {
					pr.setTheme(theme.getElement(Long.parseLong(req
							.getParameter("theme"))));
					pr.setName(req.getParameter("caption"));
					//pr.setDescription(req.getParameter("description"));

					try {
						practice.updateElement(pr);
						req.setAttribute("message",
								"Практика \"" + pr.getName() + "\" изменена.");
					} catch (Exception e) {
						req.setAttribute("message",
								"Попытка изменить практику вызвала исключение: "
										+ e.getMessage());
						e.printStackTrace();
					}
				}
				req.setAttribute("widget", "edit_practice");
				req.setAttribute("action", "/tcs/practice/edit?practice_id="
						+ pr.getLecPracId());
				req.setAttribute("practice", pr);
				req.getSession().setAttribute("listThemes",
						theme.getAllElements());

				outputPage("practice/practice_form.jsp", req, res);

			} catch (ObjectNotFoundException e) {
				res.sendRedirect(req.getContextPath() + "/tcs/practice/add");
			}
		}

	}

	private void listPractice(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		// TODO For tVinsent
		DAO<Practice> practiceDAO = dao.getPracticeDAO();
		req.setAttribute("widget", "practice");
		System.out.println(practiceDAO.getAllElements());
		req.getSession().setAttribute("listPractice",
				practiceDAO.getAllElements());
		outputPage("practice/practice.jsp", req, res);
	}

	private boolean validatePracticeForm(HttpServletRequest req) {
		// TODO Auto-generated method stub
		return true;
	}

}
